from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import json
import requests
import os
import asyncio

app = FastAPI()

DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "sk-8ee893ebae0c46e4bbb4da914bb26989"

class ChatRequest(BaseModel):
    message: str

async def stream_deepseek_response(message: str):
    if not DEEPSEEK_API_KEY:
        raise HTTPException(status_code=500, detail="DeepSeek API key not configured")

    headers = {
        'Authorization': f'Bearer {DEEPSEEK_API_KEY}',
        'Content-Type': 'application/json'
    }

    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "user", "content": message}
        ],
        "stream": True
    }

    try:
        with requests.post(DEEPSEEK_API_URL, json=payload, headers=headers, stream=True) as response:
            response.raise_for_status()

            for line in response.iter_lines():
                print(f"line: {line}")
                if line:
                    line = line.decode('utf-8')
                    print(f"decode line: {line}")
                    if line.startswith('data: '):
                        data_line = line[6:]
                        if data_line == '[DONE]':
                            yield 'data: [DONE]\n\n'
                            break
                        try:
                            data_json = json.loads(data_line)
                            if 'choices' in data_json and len(data_json['choices']) > 0:
                                delta = data_json['choices'][0].get('delta', {})
                                if 'content' in delta:
                                    content = delta['content']
                                    yield f'data: {json.dumps({"content": content})}\n\n'
                        except json.JSONDecodeError:
                            continue
                        await asyncio.sleep(0)

    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"API request failed: {str(e)}")

@app.post("/api/chat")
async def chat_stream(request_data: ChatRequest):
    if not request_data.message:
        raise HTTPException(status_code=400, detail="Message is required")

    return StreamingResponse(
        stream_deepseek_response(request_data.message),
        media_type="text/event-stream",
        headers={
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        }
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5000)
